package com.ihr360.insurance.eventhandler;

import com.ihr360.event.annonation.RestEventListener;
import com.ihr360.insurance.model.dto.benefits.MandatoryBenefitsMode;
import com.ihr360.insurance.service.MandatoryBenefitsModeService;
import com.ihr360.validation.ValidationUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author Stone.Shi
 * @description
 * @date 2018-03-20 18:25:47.
 */
@Component
public class MandatoryBenefitsModeRestEventListener implements RestEventListener<MandatoryBenefitsMode, Long> {

    private static final String ERROR_CODE_EMPTY = "编码不能为空";
    private static final String CODE_EMPTY_INFO = "该编码值已存在，请填写其他值";
    private static final String ERROR_NAME_EMPTY = "名称不能为空";
    private static final String NAME_EMPTY_INFO = "该名称已存在，请填写其他值";

    @Autowired
    private MandatoryBenefitsModeService service;

    @Override
    public void beforeCreate(MandatoryBenefitsMode mandatoryBenefitsMode) {
        String code = mandatoryBenefitsMode.getCode();
        ValidationUtils.rejectIfEmpty(code, "", ERROR_CODE_EMPTY);
        boolean codeExisted = service.isCodeExisted(code);
        if (codeExisted) {
            ValidationUtils.reject("", CODE_EMPTY_INFO);
        }
        String name = mandatoryBenefitsMode.getName();
        ValidationUtils.rejectIfEmpty(code, "", ERROR_NAME_EMPTY);
        boolean nameExisted = service.isNameExisted(name);
        if (nameExisted) {
            ValidationUtils.reject("", NAME_EMPTY_INFO);
        }
    }

    @Override
    public void beforeUpdate(Long id, Map<String, Object> source, MandatoryBenefitsMode mandatoryBenefitsMode) {
        if (source.containsKey(MandatoryBenefitsMode.Field.code)) {
            Object codeObject = source.get(MandatoryBenefitsMode.Field.code);
            ValidationUtils.rejectIfEmpty(codeObject, "", ERROR_CODE_EMPTY);
            String code = String.valueOf(codeObject);
            if (!code.equals(mandatoryBenefitsMode.getCode())) {
                boolean codeExisted = service.isCodeExisted(code);
                if (codeExisted) {
                    ValidationUtils.reject("", CODE_EMPTY_INFO);
                }
            }
        }

        if (source.containsKey(MandatoryBenefitsMode.Field.name)) {
            Object nameObject = source.get(MandatoryBenefitsMode.Field.name);
            ValidationUtils.rejectIfEmpty(nameObject, "", ERROR_NAME_EMPTY);
            String name = String.valueOf(nameObject);
            if (!name.equals(mandatoryBenefitsMode.getName())) {
                boolean nameExisted = service.isNameExisted(name);
                if (nameExisted) {
                    ValidationUtils.reject("", NAME_EMPTY_INFO);
                }
            }
        }
    }
}
